#
# @lc app=leetcode.cn id=20 lang=python3
#
# [20] 有效的括号
#

# @lc code=start
# class Solution:
#     def isValid(self, s: str) -> bool:
#         # 用栈实现
#         stack = []             
#         # stack.append(s[0]) # 栈初始化
#         for i in range(0, len(s)):
#             if stack:
#                 top = stack[-1] #
#             else:
#                 top = None
#             match s[i]:
#                 case '(':
#                     stack.append(s[i])
#                 case ')':
#                     if top == '(':
#                         stack.pop() # 成对()
#                     else:
#                         stack.append(s[i])
#                 case '{':
#                     stack.append(s[i])
#                 case '}':
#                     if top == '{':
#                         stack.pop()
#                     else:
#                         stack.append(s[i])
#                 case '[':
#                     stack.append(s[i])
#                 case ']':
#                     if top == '[':
#                         stack.pop()
#                     else:
#                         stack.append(s[i])
#         if stack:
#             return False
#         else:
#             return True
class Solution:
    def isValid(self, s: str) -> bool:
        if len(s) % 2 == 1:
            return False
        # 用了字典映射,简化了if else判断
        pairs = {
            ")": "(",
            "]": "[",
            "}": "{",
        }
        stack = list()
        for ch in s:
            # 右括号
            if ch in pairs:
                # 无法配对
                if not stack or stack[-1] != pairs[ch]:
                    return False
                else:
                    stack.pop()
            # 左括号
            else:
                stack.append(ch)
        
        return not stack
# @lc code=end

